<template>
  <div class="floor-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>楼层管理</h2>
      <p>管理音乐节场馆的楼层信息，包括楼层名称、场馆、状态等</p>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="searchForm" inline>
        <el-form-item label="场馆">
          <el-select v-model="searchForm.venueId" placeholder="请选择场馆" clearable filterable style="width: 250px">
            <el-option v-for="venue in venueOptions" :key="venue.id"
              :label="`${venue.name} (${venue.city}, ${venue.country})`" :value="venue.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="请输入楼层名称或描述" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button v-if="hasPermission(ALL_PERMISSIONS.FLOOR_CREATE)" type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>
        新增楼层
      </el-button>
      <el-button v-if="hasPermission(ALL_PERMISSIONS.FLOOR_CREATE)" @click="handleExport">
        <el-icon>
          <Download />
        </el-icon>
        导出数据
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table v-loading="loading" :data="tableData" border stripe style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" align="center" />

        <el-table-column label="场馆" min-width="200">
          <template #default="{ row }">
            <div class="venue-info">
              <el-tag type="primary" size="small">{{ row.venue.name }}</el-tag>
              <div class="venue-location">
                <span class="city">{{ row.venue.city }}</span>
                <span class="country">{{ row.venue.country }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="楼层名称" min-width="120" />

        <el-table-column prop="level" label="楼层号" width="100" align="center">
          <template #default="{ row }">
            <span v-if="row.level">{{ row.level }}F</span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>

        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.description">{{ row.description }}</span>
            <span v-else class="text-muted">暂无描述</span>
          </template>
        </el-table-column>

        <el-table-column prop="floorPlanUrl" label="平面图" width="120" align="center">
          <template #default="{ row }">
            <div v-if="row.floorPlanUrl" class="floor-plan-preview">
              <el-image :src="row.floorPlanUrl" :preview-src-list="[row.floorPlanUrl]" fit="cover"
                style="width: 60px; height: 40px; border-radius: 4px;" preview-teleported>
                <template #error>
                  <div class="image-error">
                    <el-icon>
                      <Picture />
                    </el-icon>
                  </div>
                </template>
              </el-image>
              <div class="floor-plan-actions">
                                 <el-button class="text-button" size="small" @click="handleViewFloorPlan(row)">
                   查看
                  </el-button>
              </div>
            </div>
            <span v-else class="text-muted">暂无平面图</span>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'ACTIVE' ? 'success' : 'danger'" size="small">
              {{ row.status === 'ACTIVE' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>

        <el-table-column prop="updatedAt" label="更新时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.updatedAt) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button v-if="hasPermission(ALL_PERMISSIONS.FLOOR_READ)" class="text-button" size="small"
              @click="handleView(row)">
              查看
            </el-button>

            <el-button v-if="hasPermission(ALL_PERMISSIONS.FLOOR_UPDATE)" class="text-button" size="small"
              @click="handleEdit(row)">
              编辑
            </el-button>

                         <el-button v-if="hasPermission(ALL_PERMISSIONS.FLOOR_UPDATE)" class="text-button" size="small"
               @click="handleManageFloorPlan(row)">
               平面图
              </el-button>

                         <el-button v-if="hasPermission(ALL_PERMISSIONS.FLOOR_ENABLE) && row.status === 'INACTIVE'" class="text-button"
               size="small" @click="handleEnable(row)">
               启用
              </el-button>

                         <el-button v-if="hasPermission(ALL_PERMISSIONS.FLOOR_DISABLE) && row.status === 'ACTIVE'" class="text-button"
               size="small" @click="handleDisable(row)">
               禁用
              </el-button>

                         <el-button v-if="hasPermission(ALL_PERMISSIONS.FLOOR_DELETE)" class="text-button text-danger" size="small"
               @click="handleDelete(row)">
               删除
              </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination v-model="pagination.page" v-model:page-size="pagination.limit" :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total" layout="total, sizes, prev, pager, next, jumper" @update:page-size="handleSizeChange"
        @update:current-page="handleCurrentChange" />
    </div>

    <!-- 楼层编辑对话框 -->
    <FloorDialog v-model:visible="dialogVisible" :floor-data="currentFloor" :venue-options="venueOptions"
      @success="handleSuccess" />

    <!-- 平面图管理对话框 -->
    <FloorPlanManager v-model:visible="floorPlanManagerVisible" :floor="currentFloor" @success="handleSuccess" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Download, Picture } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { floorApi, type Floor, type VenueOption } from '@/api/floor'
import { getVenues, type VenueData } from '@/api/venue'
import FloorDialog from './components/FloorDialog.vue'
import FloorPlanManager from './components/FloorPlanManager.vue'
import { formatDate } from '@/utils/format'
import { ALL_PERMISSIONS } from '@/constants/permissions'

const userStore = useUserStore()

// 权限检查
const hasPermission = (permission: string) => {
  return userStore.hasPermission(permission)
}

// 响应式数据
const loading = ref(false)
const tableData = ref<Floor[]>([])
const dialogVisible = ref(false)
const currentFloor = ref<Floor | null>(null)
const floorPlanManagerVisible = ref(false)
const venueOptions = ref<VenueOption[]>([])

// 搜索表单
const searchForm = reactive({
  venueId: undefined as number | undefined,
  keyword: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 获取场馆选项
const fetchVenueOptions = async () => {
  try {
    const response = await getVenues({ page: 1, pageSize: 1000 })
    if (response.success && response.data) {
      venueOptions.value = response.data.data.map(venue => ({
        id: venue.id!,
        name: venue.name,
        city: venue.city,
        country: venue.country
      }))
    }
  } catch (error) {
    console.error('获取场馆列表失败:', error)
  }
}

// 获取楼层列表
const fetchFloorList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      venueId: searchForm.venueId,
      keyword: searchForm.keyword || undefined
    }

    const response = await floorApi.getList(params)
    const { data, pagination: paginationData } = response.data

    tableData.value = data
    pagination.total = paginationData.total
    pagination.page = paginationData.page
    pagination.limit = paginationData.limit
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '获取楼层列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchFloorList()
}

// 重置搜索
const handleReset = () => {
  searchForm.venueId = undefined
  searchForm.keyword = ''
  pagination.page = 1
  fetchFloorList()
}

// 新增楼层
const handleAdd = () => {
  currentFloor.value = null
  dialogVisible.value = true
}

// 查看楼层
const handleView = (row: Floor) => {
  currentFloor.value = row
  dialogVisible.value = true
}

// 编辑楼层
const handleEdit = (row: Floor) => {
  currentFloor.value = row
  dialogVisible.value = true
}

// 启用楼层
const handleEnable = async (row: Floor) => {
  try {
    await ElMessageBox.confirm(
      `确定要启用楼层"${row.name}"吗？`,
      '确认启用',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await floorApi.enable(row.id)
    ElMessage.success('楼层启用成功')
    fetchFloorList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '启用失败')
    }
  }
}

// 禁用楼层
const handleDisable = async (row: Floor) => {
  try {
    await ElMessageBox.confirm(
      `确定要禁用楼层"${row.name}"吗？`,
      '确认禁用',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await floorApi.disable(row.id)
    ElMessage.success('楼层禁用成功')
    fetchFloorList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '禁用失败')
    }
  }
}

// 删除楼层
const handleDelete = async (row: Floor) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除楼层"${row.name}"吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )

    await floorApi.delete(row.id)
    ElMessage.success('楼层删除成功')
    fetchFloorList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

// 导出数据
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  fetchFloorList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchFloorList()
}

// 操作成功回调
const handleSuccess = () => {
  fetchFloorList()
}

// 查看平面图
const handleViewFloorPlan = (row: Floor) => {
  if (row.floorPlanUrl) {
    ElMessageBox.alert(
      `<img src="${row.floorPlanUrl}" alt="Floor Plan" style="max-width: 100%; max-height: 80vh; display: block; margin: 0 auto; border-radius: 8px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);">`,
      `楼层平面图 - ${row.name}`,
      {
        customClass: 'floor-plan-preview-dialog',
        dangerouslyUseHTMLString: true,
        confirmButtonText: '关闭',
        customStyle: {
          width: '90%',
          height: '90%'
        }
      }
    )
  }
}

// 管理平面图
const handleManageFloorPlan = (row: Floor) => {
  currentFloor.value = row
  floorPlanManagerVisible.value = true
}

// 页面加载时获取数据
onMounted(() => {
  fetchVenueOptions()
  fetchFloorList()
})
</script>

<style scoped lang="scss">
.floor-list {
  padding: 20px;

  .page-header {
    margin-bottom: 20px;

    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }

    p {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .search-bar {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
  }

  .action-bar {
    margin-bottom: 20px;

    .el-button {
      margin-right: 10px;
    }
  }

  .table-container {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    overflow: hidden;
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .text-muted {
    color: #c0c4cc;
  }

  .text-danger {
    color: #f56c6c;
  }

  .text-button {
    color: #409eff;
    background: transparent;
    border: none;
    padding: 0;
    font-size: 14px;
    
    &:hover {
      color: #66b1ff;
      background: transparent;
    }
    
    &:focus {
      color: #409eff;
      background: transparent;
    }
  }

  .venue-info {
    .venue-location {
      margin-top: 5px;
      font-size: 12px;
      color: #909399;

      .city {
        margin-right: 8px;
      }

      .country {
        color: #c0c4cc;
      }
    }
  }

  .floor-plan-preview {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 5px 0;
  }

  .floor-plan-actions {
    display: flex;
    gap: 5px;
  }

  .image-error {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60px;
    height: 40px;
    background-color: #f5f7fa;
    border-radius: 4px;
    border: 1px dashed #dcdfe6;
    color: #909399;
    font-size: 20px;
  }

  .floor-plan-preview-dialog {
    .el-dialog__body {
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #fff;
    }
  }
}
</style>
